package com.ruoyi.crm.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.crm.consts.Constants;
import com.ruoyi.crm.domain.AssignRecord;
import com.ruoyi.crm.domain.CrmUser;
import com.ruoyi.crm.domain.DictData;
import com.ruoyi.crm.domain.dto.BusinessDTO;
import com.ruoyi.crm.domain.vo.BusinessVO;
import com.ruoyi.crm.domain.vo.MongoBusinessRecordVO;
import com.ruoyi.crm.domain.vo.ResourceGainVO;
import com.ruoyi.crm.enums.StatusType;
import com.ruoyi.crm.mapper.AssignRecordMapper;
import com.ruoyi.crm.mapper.DictDataMapper;
import com.ruoyi.crm.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import com.ruoyi.crm.mapper.BusinessMapper;
import com.ruoyi.crm.domain.Business;
import com.ruoyi.crm.service.IBusinessService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商机管理Service业务层处理
 *
 * @author ruoyi
 * @date 2022-06-07
 */
@Service
@Transactional
public class BusinessServiceImpl implements IBusinessService
{
    @Autowired
    private BusinessMapper businessMapper;
    @Resource
    private MongoTemplate mongoTemplate;
    @Resource
    private AssignRecordMapper assignRecordMapper;
    @Resource
    private DictDataMapper dictDataMapper;
    @Resource
    private UserMapper userMapper;

    /**
     * 查询商机管理
     *
     * @param id 商机管理主键
     * @return 商机管理
     */
    @Override
    public Business selectBusinessById(Long id)
    {
        return businessMapper.selectBusinessById(id);
    }

    @Override
    public List<Business> selectBusinessList(Business business) {
        return businessMapper.selectBusinessList(business);
    }

    /**
     * 查询商机管理列表
     *
     * @param business 商机管理
     * @return 商机管理
     */
    @Override
    public List<BusinessVO> selectBusinessVOList(Business business)
    {
        business.setUserName(SecurityUtils.getUsername());
        return businessMapper.selectBusinessVOLs(business);
    }

    @Override
    public List<BusinessVO> selectBusinessPoolList(Business business) {
        business.setStatus(StatusType.RECOVERY.getValue());
        return businessMapper.selectBusinessPoolList(business);
    }

    /**
     * 查询出mongodb中数据
     * @param businessId
     * @return
     */
    @Override
    public List<MongoBusinessRecordVO> businessRecordData(Long businessId) {
        Query query = new Query(Criteria.where("businessId").is(businessId));
        //通过创建时间倒序排序
        query.with(Sort.by(Sort.Order.desc("createTime")));
        List<MongoBusinessRecordVO> mongoBusinessRecordVOS =
                mongoTemplate.find(query, MongoBusinessRecordVO.class,"business_recorddb");
        return mongoBusinessRecordVOS;
    }

    /**
     * 跟进商机记录：
     * 1、修改商机跟进中状态：2
     * 2、将字典表中，所有关于沟通要素查出来，将label放入到MongoDB中
     * 3、新增在商机记录在MongoDB
     * @param busines
     */
    @Override
    public void addRecord(BusinessDTO busines) {
        Business business = new Business();
        dtoToBuiness(busines,business);
        business.setStatus(StatusType.FOLLOWING.getValue());
        businessMapper.updateBusiness(business);

        MongoBusinessRecordVO cordVO = new MongoBusinessRecordVO();
        cordVO.setKeyItems(busines.getKeyItems());
        //沟通重点
        List<DictData> dictDataList = dictDataMapper.
                selectCommunicationPoint(Constants.COMMUNICATION_POINT);
        ArrayList<String> ks = new ArrayList<>();
        busines.getKeyItemsArray().forEach(b -> {
            for (int i = 0; i < dictDataList.size(); i++) {
                if(b.equals(dictDataList.get(i).getDictValue())){
                   ks.add(dictDataList.get(i).getDictLabel());
                }
            }
        });
        cordVO.setKeys(ks);

        LoginUser loginUser = SecurityUtils.getLoginUser();
        cordVO.setBusinessId(Long.parseLong(busines.getBusinessId()));
        cordVO.setCreateBy(loginUser.getUsername());
        cordVO.setCreateTime(new Timestamp(System.currentTimeMillis()));
        cordVO.setNextTime(busines.getNextTime());
        cordVO.setRecord(busines.getRecord());
        cordVO.setTrackStatus(busines.getTrackStatus());
        mongoTemplate.save(cordVO);
    }

    /**
     * 1、将字典表中关于踢回公海原因查询出来，用于修改商机表中的other_intention用来标注踢回公海原因，暂时没找到踢回公海原因的字段
     * 2、修改该商机状态为：3
     * @param busId
     * @param busReasonsId
     * @return
     */
    @Override
    public AjaxResult backBusiness(String busId, String busReasonsId) {
        DictData dictData = dictDataMapper.selectBackBusinessStatus(busReasonsId);

        Business business = new Business();
        business.setId(Long.parseLong(busId));
        business.setOtherIntention(dictData.getDictLabel());
        business.setLastUpdateTime(DateUtils.getNowDate());
        business.setStatus(StatusType.FALSE.getValue());
        businessMapper.updateBusiness(business);
        return AjaxResult.success();
    }

    /**
     * 1、改变捞取创建人，捞取时间
     * 2、改变记录表中的最新分配人状态
     * 3、新增记录表 捞取的记录
     * @param resourceGainVO
     * @return
     */
    @Override
    public AjaxResult businessGain(ResourceGainVO resourceGainVO) {
        List<Business> businesses = businessMapper.selectBusinessListById(resourceGainVO.getIds());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        businesses.forEach(b -> {
            b.setCreateBy(loginUser.getUsername());
            b.setLastUpdateTime(DateUtils.getNowDate());
            b.setStatus(StatusType.UNFOLLOWED.getValue());
            businessMapper.updateBusiness(b);

            assignRecordMapper.updateClueLatest(resourceGainVO.getIds());

            AssignRecord as = new AssignRecord();
            as.setType("1");
            as.setLatest("1");
            as.setAssignId(b.getId());
            as.setUserId(loginUser.getUserId());
            as.setDeptId(loginUser.getDeptId());
            as.setCreateBy(loginUser.getUsername());
            as.setUserName(loginUser.getUsername());
            as.setCreateTime(DateUtils.getNowDate());
            assignRecordMapper.insertAssignRecord(as);
        });
        return AjaxResult.success("捞取成功");
    }

    /**
     * 1、将分配用户的信息查询出来
     * 2、修改元商机表 status：1  transfer：1  last_update_time  create_by
     * 3、修改元分配表中 latest：0
     * 4、新增商机分配记录
     * @param resourceGainVO
     * @return
     */
    @Override
    public AjaxResult assignment(ResourceGainVO resourceGainVO) {
        CrmUser crmUser = userMapper.queryById(resourceGainVO.getUserId().longValue());
        resourceGainVO.getIds().forEach(i -> {
            Business business = new Business();
            business.setId(i);
            business.setStatus("1");
            business.setTransfer("1");
            business.setLastUpdateTime(DateUtils.getNowDate());
            business.setCreateBy(crmUser.getUserName());
            businessMapper.updateBusiness(business);

            AssignRecord assignRecord = new AssignRecord();
            assignRecord.setType("1");
            assignRecord.setLatest("1");
            assignRecord.setAssignId(i);
            assignRecord.setUserId(crmUser.getUserId());
            assignRecord.setDeptId(crmUser.getDeptId());
            assignRecord.setCreateBy(crmUser.getUserName());
            assignRecord.setUserName(crmUser.getUserName());
            assignRecord.setCreateTime(DateUtils.getNowDate());
            assignRecordMapper.insertAssignRecord(assignRecord);
        });
        assignRecordMapper.updateClueLatest(resourceGainVO.getIds());
        return AjaxResult.success();
    }

    @Override
    public Business querySubjectByBusId(Long busId) {
        return businessMapper.querySubjectByBusId(busId);
    }

    public void dtoToBuiness(BusinessDTO bs,Business b){
        BeanUtils.copyProperties(bs,b);
        b.setStatus(StatusType.FOLLOWING.getValue());
        b.setId(Long.parseLong(bs.getBusinessId()));
        b.setUpdateBy(SecurityUtils.getUsername());
        b.setUpdateTime(DateUtils.getNowDate());
    }

    /**
     * 新增商机管理
     *
     * @param business 商机管理
     * @return 结果
     */
    @Override
    public int insertBusiness(Business business)
    {
        business.setCreateTime(DateUtils.getNowDate());
        business.setCreateBy(SecurityUtils.getUsername());
        businessMapper.insertBusiness(business);

        LoginUser loginUser = SecurityUtils.getLoginUser();
        //需要想分配表中添加数据
        AssignRecord record = new AssignRecord();
        record.setCreateTime(DateUtils.getNowDate());
        record.setAssignId(business.getId());
        record.setCreateBy(loginUser.getUsername());
        record.setUserName(loginUser.getUsername());
        record.setType("1");
        record.setLatest("1");

        //获取所属人部分
        record.setDeptId(loginUser.getDeptId());
        record.setUserId(loginUser.getUserId());
        return assignRecordMapper.insertAssignRecord(record);
    }

    /**
     * 修改商机管理
     *
     * @param business 商机管理
     * @return 结果
     */
    @Override
    public int updateBusiness(Business business)
    {
        return businessMapper.updateBusiness(business);
    }

    /**
     * 批量删除商机管理
     *
     * @param ids 需要删除的商机管理主键
     * @return 结果
     */
    @Override
    public int deleteBusinessByIds(Long[] ids)
    {
        return businessMapper.deleteBusinessByIds(ids);
    }

    /**
     * 删除商机管理信息
     *
     * @param id 商机管理主键
     * @return 结果
     */
    @Override
    public int deleteBusinessById(Long id)
    {
        return businessMapper.deleteBusinessById(id);
    }
}
